<script lang="ts" setup>
import UseTab from '@/components/use-tabs/index.vue'
import TodoListItem from './components/todo-list-item/index.vue'
import UserInfoListItem from './components/user-info-list-item/index.vue'
import { TaskUpdates, TodoTask } from '@/models/task'
import NotData from '@/components/NotData.vue'
import { Status } from '@/models/sys'
import { InsightItem, Student, UserInfoUpdates, UserInsight } from '@/models/user-info'
import { checkLatestTask } from '@/service/index/task'
import { checkLatestUserInfo } from '@/service/index/user-info'
import PortraitDialog from './components/portrait-dialog/index.vue'
import _ from 'lodash'
import WdPicker from 'wot-design-uni/components/wd-picker/wd-picker.vue'

const props = withDefaults(
  defineProps<{
    isTab: boolean
  }>(),
  {},
)

watch(
  () => props.isTab,
  (val) => {
    if (val) {
      tabRefresh()
    } else {
      todosMessageSubscribe.stop()
      usersMessageSubscribe.stop()
    }
  },
)

onMounted(() => {
  if (tabState.active === 0) openTodosMessageSubscribe()
  if (tabState.active === 1) usersTodosMessageSubscribe()
})

const todosMessageSubscribe = useMessageSubscribe()

function openTodosMessageSubscribe() {
  todosMessageSubscribe.start(checkLatestTask, {
    onMessage(data: TaskUpdates) {
      if (data.latest.length) {
        todoMessageParams.value.latest_id = data.latest[0].id
        todosMessageSubscribe.setExtraParams(todoMessageParams.value)
        // @ts-ignore
        tabState.list[0].badgeProps.modelValue = data.todo_count

        if (todoItems.value.length) {
          todoItems.value.unshift(...data.latest)
        } else {
          pagingTodoListRef.value?.reload()
          // pagingTodoListRefresh()
        }
      }
    },
  })
}

const usersMessageSubscribe = useMessageSubscribe()

function usersTodosMessageSubscribe() {
  usersMessageSubscribe.start(checkLatestUserInfo, {
    onMessage(data: UserInfoUpdates) {
      if (data.latest.length) {
        usersMessageParams.value.latest_id = data.latest[0].id
        usersMessageSubscribe.setExtraParams(todoMessageParams.value)

        if (userInfoItems.value.length) {
          userInfoItems.value.unshift(...data.latest)
        } else {
          pagingUserInfoListRef.value?.reload()
          // pagingUserInfoListRefresh()
        }
      }
    },
  })
}

onUnmounted(() => {
  todosMessageSubscribe.stop()
  usersMessageSubscribe.stop()
})

const todoMessageParams = ref({
  latest_id: 0,
})

const usersMessageParams = ref({
  latest_id: 0,
})

const tabState = reactive({
  active: 0,
  list: [
    {
      title: '待办事项',
      value: 0,
      badgeProps: {
        modelValue: 0,
        max: 99,
        right: '-8px',
      },
      isLoad: false,
    },
    { title: 'AI提取信息确认', value: 1, isLoad: false },
  ],
})

watch(
  () => tabState.active,
  () => {
    tabRefresh()
  },
)

function tabRefresh() {
  if (tabState.active === 0) {
    usersMessageSubscribe.stop()
    openTodosMessageSubscribe()
    pagingTodoListRefresh()
  } else if (tabState.active === 1) {
    todosMessageSubscribe.stop()
    usersTodosMessageSubscribe()
    pagingUserInfoListRefresh()
  }
}

const { todoTotal, ...callback } = useChat()

/**
 * 待办事项列表
 */
const pagingTodoListRef = ref()
const todoItems = ref<TodoTask[]>([])

async function queryTodoList(page: number, per_page: number) {
  const listData = await callback.getTaskList({
    page,
    per_page,
  })

  if (page === 1 && listData.length) {
    todoMessageParams.value.latest_id = listData[0].id
    todosMessageSubscribe.setExtraParams(todoMessageParams.value)
  }
  tabState.list[0].isLoad = true
  // @ts-ignore
  tabState.list[0].badgeProps.modelValue = todoTotal.value
  pagingTodoListRef.value.complete(listData)
}

/**
 * AI信息确认列表
 */
const userInfoItems = ref<InsightItem[]>([])
const pagingUserInfoListRef = ref()
async function queryUserInfoList(page: number, per_page: number) {
  const listData = await callback.getUserInfoList({
    page,
    per_page,
  })
  if (page === 1 && listData.length) {
    usersMessageParams.value.latest_id = listData[0].id
    usersMessageSubscribe.setExtraParams(usersMessageParams.value)
  }
  tabState.list[1].isLoad = true
  pagingUserInfoListRef.value.complete(listData)
}
function openChat(item: TodoTask) {
  wx.qy.openEnterpriseChat({
    externalUserIds: item.customer.external_user_id,
    userIds: '',
    groupName: '',
    chatId: '',
    success: (res) => {
      console.log(res)
    },
    fail(err) {
      uni.showModal({
        title: '打开失败',
        content: JSON.stringify(err),
        showCancel: false,
        confirmText: '好的',
      })
      console.log(err)
    },
  })
}

function doneChange(item: TodoTask) {
  callback.taskDone({ id: item.id, status: Status.Yes }, () => {
    pagingTodoListRefresh()
    uni.showToast({
      title: '操作成功',
    })
  })
}

function pagingTodoListRefresh() {
  pagingTodoListRef.value?.refresh()
}

function pagingUserInfoListRefresh() {
  pagingUserInfoListRef.value?.refresh()
}

/** 丢弃 */
function discard(item: InsightItem) {
  uni.showModal({
    title: '提示',
    content: '确认丢弃该用户洞察吗？',
    success: (res) => {
      if (res.confirm) {
        callback.discardUserInfo({ id: item.id }, () => {
          uni.showToast({
            title: '操作成功',
          })
          pagingUserInfoListRefresh()
        })
      }
    },
  })
}
/** 确定消息 */
function confirm(item: InsightItem) {
  if (!item.student_id) {
    uni.showToast({
      title: '请选择学生',
      icon: 'none',
    })
    return
  }
  uni.showModal({
    title: '提示',
    content: '确认该用户洞察吗？',
    success: (res) => {
      if (res.confirm) {
        callback.confirmUserInfo({ id: item.id, student_id: item.student_id }, () => {
          uni.showToast({
            title: '操作成功',
          })
          pagingUserInfoListRefresh()
        })
      }
    },
  })
}

/** 编辑用户洞察 */
function editInsightsUser(val) {
  callback.editUserInsight(val, () => {
    uni.showToast({
      title: '编辑成功',
      icon: 'none',
    })
  })
}

/** 删除用户洞察 */
function removeUserInsight(item: UserInsight) {
  callback.deleteUserInfo({ id: item.id }, () => {
    uni.showToast({
      title: '删除成功',
      icon: 'none',
    })
  })
}

const portraitDialogRef = ref<InstanceType<typeof PortraitDialog>>()
/** 编辑用户画像 */
function portrait(item: InsightItem) {
  portraitDialogRef.value?.open(item)
}

const pickerSelectRef = ref<InstanceType<typeof WdPicker>>()
const selectState = reactive<{
  list: Student[]
  value: number | undefined
  label: string
  id: number
}>({
  list: [],
  value: undefined,
  label: '',
  id: 0,
})

/** 选择用户 */
function pickerSelect(item: InsightItem) {
  const _item = _.cloneDeep(item)

  selectState.list = _item.students || []
  selectState.id = _item.id
  selectState.value = _item.student_id
  pickerSelectRef.value.open()
}

function pickerConfirm(val: any) {
  selectState.value = val.selectedItems.id

  const index = selectState.list.findIndex((item) => item.id === selectState.value)

  if (index === -1) {
    return
  }

  const listIndex = userInfoItems.value.findIndex((item) => item.id === selectState.id)
  if (listIndex === -1) {
    return
  }
  const item = userInfoItems.value[listIndex]
  item.student_id = val.selectedItems.id
  item.student_name = val.selectedItems.real_name
}

function cancel() {
  selectState.list = []
  selectState.id = 0
  selectState.value = 0
}
</script>

<template>
  <view class="relative pt-2" style="height: 100%">
    <UseTab :list="tabState.list" v-model="tabState.active"></UseTab>
    <view class="scroll-views" v-show="tabState.active === 0">
      <z-paging
        ref="pagingTodoListRef"
        v-model="todoItems"
        @query="queryTodoList"
        :fixed="false"
        :default-page-size="20"
        auto-show-back-to-top
        show-refresher-when-reload
      >
        <template #empty>
          <NotData text="暂无更多待回复消息"></NotData>
        </template>
        <view class="list" v-for="item in todoItems" :key="item.id">
          <TodoListItem
            :itemData="item"
            :isTab="tabState.active === 0"
            @open-chat="() => openChat(item)"
            @done-change="() => doneChange(item)"
          ></TodoListItem>
        </view>
        <view class="h-10"></view>
      </z-paging>
    </view>
    <view class="scroll-views" v-show="tabState.active === 1">
      <z-paging
        ref="pagingUserInfoListRef"
        v-model="userInfoItems"
        @query="queryUserInfoList"
        :fixed="false"
        :default-page-size="20"
        auto-show-back-to-top
        show-refresher-when-reload
      >
        <view class="list" v-for="item in userInfoItems" :key="item.id">
          <UserInfoListItem
            :itemData="item"
            :isTab="tabState.active === 1"
            @confirm="() => confirm(item)"
            @discard="() => discard(item)"
            @editInsightsUser="(val) => editInsightsUser(val)"
            @removeUserInsight="(val) => removeUserInsight(val)"
            @portrait="() => portrait(item)"
            @pickerSelect="() => pickerSelect(item)"
          ></UserInfoListItem>
        </view>
        <view class="h-10"></view>
      </z-paging>
    </view>
    <!-- 编辑用户画像 -->
    <PortraitDialog
      ref="portraitDialogRef"
      :refresh="() => pagingUserInfoListRefresh()"
    ></PortraitDialog>

    <wd-picker
      :columns="selectState.list"
      ref="pickerSelectRef"
      title="选择学生"
      value-key="id"
      :columns-height="240"
      :z-index="1000"
      confirm-button-text="确认"
      label-key="real_name"
      v-model="selectState.value"
      @confirm="pickerConfirm"
      @cancel="cancel"
      clearable
    />
  </view>
</template>

<style lang="scss" scoped>
.scroll-views {
  height: calc(100% - 110rpx);
  margin-top: 10rpx;
}
</style>
